package com.xh.bussiness.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.course.bean.dto.CourseDto;
import com.xh.bussiness.course.bean.dto.CourseIndexDto;
import com.xh.bussiness.course.bean.request.CourseIndexRequest;
import com.xh.bussiness.course.bean.request.CourseRequest;
import com.xh.bussiness.course.constant.PrepareLessonConstants;
import com.xh.bussiness.course.dao.CourseMapper;
import com.xh.bussiness.course.model.Course;
import com.xh.bussiness.course.model.CourseIndex;
import com.xh.bussiness.course.model.PrepareLesson;
import com.xh.bussiness.course.model.PrepareUserConfig;
import com.xh.bussiness.course.service.*;
import com.xh.bussiness.resource.bean.request.MaterialCourseIndexRequest;
import com.xh.bussiness.resource.model.MaterialCourseIndex;
import com.xh.bussiness.resource.model.MaterialPrepare;
import com.xh.bussiness.resource.service.IMaterialCourseIndexService;
import com.xh.bussiness.resource.service.IMaterialPrepareService;
import com.xh.core.bean.XhPage;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;


@Service
public class CourseServiceImpl extends BaseServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private ICourseIndexService courseIndexService;
    @Autowired
    private IMaterialCourseIndexService materialCourseIndexService;
    @Autowired
    private IMaterialPrepareService materialPrepareService;
    @Autowired
    private IPrepareLessonService prepareLessonService;
    @Autowired
    private IPrepareUserConfigService prepareUserConfigService;

    @Override
    public XhPage<CourseDto> queryPage(XhPage page, CourseRequest bean) {
        page.setCurrent(bean.getCurrent());
        page.setSize(bean.getSize());
        String userId = UserUtils.getCurrentUserId();
        // 查询该用户不能备课的课程id
        List<String> courseIds = prepareUserConfigService.getUserNoPermissionCourseIds(userId);
        if (!courseIds.isEmpty()) {
            bean.setCourseIds(courseIds);
        }
        this.dao.queryByPage(page, bean);
        List<CourseDto> list = page.getRecords();
        for (CourseDto courseDto : list) {
            QueryWrapper<PrepareLesson> qw = new QueryWrapper<>();
            qw.eq("course_id", courseDto.getId());
            qw.eq("creator_id", UserUtils.getCurrentUserId());
            List<PrepareLesson> prepareLessons = prepareLessonService.queryByCondition(qw);
            for (PrepareLesson prepareLesson : prepareLessons) {
                if (prepareLesson.getCheckStatus() == PrepareLessonConstants.CheckStatus.UN_PASS) {
                    courseDto.setUnPassNum(courseDto.getUnPassNum() + 1);
                } else if (prepareLesson.getCheckStatus() == PrepareLessonConstants.CheckStatus.UN_SUBMIT) {
                    courseDto.setUnPrepared(courseDto.getUnPrepared() + 1);
                }
            }
            // 未备课的课次还包含没有备课记录的，没有备课记录 = 课次数 - 有备课记录课次数
            courseDto.setUnPrepared(courseDto.getUnPrepared() + (courseDto.getCourseIndexNum() == null ? 0 : courseDto.getCourseIndexNum()) - prepareLessons.size());
        }
        return page;
    }

    @Override
    public CourseDto queryOne(CourseRequest bean) {

        return this.dao.queryOne(bean);
    }

    @Override
    @Transactional
    public Course add(CourseRequest bean) {
        Course course = new Course();
        BeanUtils.copyProperties(bean, course);
        this.insert(course);

        Integer courseIndexNum = bean.getCourseIndexNum();
        if (courseIndexNum != null && courseIndexNum > 0) {
            List<CourseIndexRequest> courseIndexRequestList = new ArrayList<>();
            for (int i = 0; i < courseIndexNum; i++) {
                CourseIndexRequest courseIndexRequest = new CourseIndexRequest();
                courseIndexRequest.setCourseId(course.getId());
                courseIndexRequest.setCourseIndexName("第" + (i + 1) + "讲");
                courseIndexRequest.setOrderNo(i + 1);
                courseIndexRequestList.add(courseIndexRequest);
            }
            String save = courseIndexService.batchSave(courseIndexRequestList);
        }
        // 创建课程默认分组
//        prepareConfigGroupService.createDefaultGroups(course.getId());
        return course;
    }

    @Override
    @Transactional
    public Course modify(CourseRequest bean) {
        Course course = this.getById(bean.getId());
        if (null == course) {
            return null;
        }

        Integer courseIndexNum = course.getCourseIndexNum();

        if (!StringUtils.isEmpty(bean.getCourseName())) {
            course.setCourseName(bean.getCourseName());
        }
        if (!StringUtils.isEmpty(bean.getSubjectId())) {
            course.setSubjectId(bean.getSubjectId());
        }
        if (!StringUtils.isEmpty(bean.getGradeRangeId())) {
            course.setGradeRangeId(bean.getGradeRangeId());
        }
        if (!StringUtils.isEmpty(bean.getGradeId())) {
            course.setGradeId(bean.getGradeId());
        }
        if (null != bean.getYear()) {
            course.setYear(bean.getYear());
        }
        if (!StringUtils.isEmpty(bean.getCourseTypeId())) {
            course.setCourseTypeId(bean.getCourseTypeId());
        }
        if (!StringUtils.isEmpty(bean.getSemesterId())) {
            course.setSemesterId(bean.getSemesterId());
        }
        if (null != bean.getCourseIndexNum()) {
            course.setCourseIndexNum(bean.getCourseIndexNum());
        }

        if (null != bean.getImgPath()) {
            course.setImgPath(bean.getImgPath());
        }

        this.update(course);
        if (bean.getCourseIndexNum() == null) {
            return course;
        }
        int num = bean.getCourseIndexNum() - courseIndexNum;
        if (num == 0) {
            return course;
        } else if (num < 1) {
            CourseIndexRequest courseIndexRequest = new CourseIndexRequest();
            courseIndexRequest.setCourseId(course.getId());
            List courseIndexs = courseIndexService.query(courseIndexRequest);
            int size = courseIndexs.size();
            int index = Math.abs(num);
            for (int i = 1; i <= index; i++) {
                CourseIndexDto courseIndex = (CourseIndexDto) courseIndexs.get(size - i);
                courseIndexService.delete(courseIndex.getId());
            }
        } else {
            CourseIndexRequest request = new CourseIndexRequest();
            request.setCourseId(course.getId());
            List courseIndexs = courseIndexService.query(request);
            int size = courseIndexs.size();
            List<CourseIndex> courseIndexList = new ArrayList<>();
            for (int i = 0; i < num; i++) {
                CourseIndex courseIndex = new CourseIndex();
                courseIndex.setCourseIndexName("第" + (size + i + 1) + "讲");
                courseIndex.setCourseId(course.getId());
                courseIndex.setOrderNo(size + i + 1);
                courseIndexList.add(courseIndex);
            }
            courseIndexService.batchInsert(courseIndexList);
        }
        return course;

    }

    @Override
    public List<CourseDto> query(CourseRequest bean) {
        List<CourseDto> courseDtoList = new ArrayList<>();
        QueryWrapper<Course> qw = new QueryWrapper<>();
        if (!StringUtils.isEmpty(bean.getSubjectId())) {
            qw.eq("subject_id", bean.getSubjectId());
        }
        if (!StringUtils.isEmpty(bean.getGradeId())) {
            qw.eq("grade_id", bean.getGradeId());
        }
        if (!StringUtils.isEmpty(bean.getCourseTypeId())) {
            qw.eq("course_type_id", bean.getCourseTypeId());
        }
        if (!StringUtils.isEmpty(bean.getYear())) {
            qw.eq("year", bean.getYear());
        }
        if (!StringUtils.isEmpty(bean.getSemesterId())) {
            qw.eq("semester_id", bean.getSemesterId());
        }
        List<Course> courses = this.dao.selectList(qw);
        for (int i = 0; i < courses.size(); i++) {
            CourseDto courseDto = new CourseDto();
            Course course = courses.get(i);
            BeanUtils.copyProperties(course, courseDto);
            QueryWrapper<CourseIndex> ciQw = new QueryWrapper();
            ciQw.eq("course_id", course.getId());
            ciQw.orderByAsc("order_no");
            List<CourseIndexDto> courseIndexs = courseIndexService.selectList(ciQw, CourseIndexDto.class);

//            List<String> indexIds = courseIndexs.stream().map(CourseIndexDto::getId).collect(Collectors.toList());
//            QueryWrapper<MaterialCourseIndex> qwmc = new QueryWrapper<>();
//            qwmc.eq("material_id",bean.getMaterialId());
//            qwmc.in("course_index_id",indexIds);
//            List<MaterialCourseIndex> materialCourseIndexList = materialCourseIndexService.queryByCondition(qwmc);

            for (int j = 0; j < courseIndexs.size(); j++) {
                CourseIndexDto dto = courseIndexs.get(j);
                MaterialCourseIndexRequest mcir = new MaterialCourseIndexRequest();
                mcir.setMaterialId(bean.getMaterialId());
                mcir.setCourseIndexId(dto.getId());
                List<MaterialCourseIndex> list = materialCourseIndexService.query(mcir);
                dto.setIsExist(list.size() > 0 ? list.size() : 0);

            }
            courseDto.setCourseIndexList(courseIndexs);
            courseDtoList.add(courseDto);
        }
        return courseDtoList;
    }


    @Override
    public XhPage<CourseDto> queryNearCourseIndex(XhPage page, CourseRequest request) {

        return this.dao.queryNearCourseIndex(page, request);
    }

    @Override
    public Integer queryCourseCount(CourseRequest request) {
        QueryWrapper qw = new QueryWrapper<Course>();
        //拼装条件
        qw = prepareParams(request, qw);
        return this.selectCount(qw);
    }

    @Override
    public List<Course> queryBySubject(String subject, String name) {
        QueryWrapper qw = new QueryWrapper<Course>();
        if (!StringUtils.isEmpty(subject)) {
            qw.eq("subject_id", subject);
        }
        if (!StringUtils.isEmpty(name)) {
            qw.like("course_name", name);
        }
        return super.queryByCondition(qw);
    }

    @Override
    public String changePublishStatus(String courseId, Integer status) {
        Course course = new Course();
        course.setId(courseId);
        course.setStatus(status);
        super.update(course);
        return null;
    }

    @Override
    public Course changeCourseSetStep(String courseId, Integer step) {
        Course course = super.getById(courseId);
        if (step != null && course.getStep() != null && course.getStep() < step) {
            course.setStep(step);
            super.update(course);
        }
        return course;
    }

    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(CourseRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (!StringUtils.isEmpty(bean.getSubjectId())) {
            qw.eq("subject_id", bean.getSubjectId());
        }
        if (!CollectionUtils.isEmpty(bean.getSubjectIds())) {
            qw.in("subject_id", bean.getSubjectIds());
        }
        if (!StringUtils.isEmpty(bean.getYear())) {
            qw.eq("year", bean.getYear());
        }
        if (!CollectionUtils.isEmpty(bean.getYears())) {
            qw.in("year", bean.getYears());
        }
        if (!StringUtils.isEmpty(bean.getGradeId())) {
            qw.eq("grade_id", bean.getGradeId());
        }
        if (!CollectionUtils.isEmpty(bean.getGradeIds())) {
            qw.in("grade_id", bean.getGradeIds());
        }
        if (!StringUtils.isEmpty(bean.getSemesterId())) {
            qw.eq("semester_id", bean.getGradeId());
        }
        if (!CollectionUtils.isEmpty(bean.getSemesterIds())) {
            qw.in("semester_id", bean.getSemesterIds());
        }
        if (!StringUtils.isEmpty(bean.getCourseTypeId())) {
            qw.eq("course_type_id", bean.getCourseTypeId());
        }
        if (!CollectionUtils.isEmpty(bean.getCourseTypeIds())) {
            qw.in("course_type_id", bean.getCourseTypeIds());
        }
        return qw;
    }
}
